from ui import Win
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os

class Controller:
    ui: Win
    def __init__(self):
        self.check_vars = {}
        self.video_extensions_vars = {}
        self.subtitle_extensions_vars = {}

    def init(self, ui):
        self.ui = ui
        for var_name, var_value in [
            ("mp4", True),
            ("avi", False),
            ("mkv", False),
            ("flv", False),
            ("ts", False),
            ("mov", False),
            ("wmv", False),
            ("mp3", False),
            ("aac", True),
            ("ape", False),
            ("flac", False),
            ("wav", False),
            ("alac", False),
            ("ogg", False),
            ("srt", True),
            ("ass", True),
            ("sub", False),
            ("ssa", False),
            ("lrc", True),
            ("krc", False),
            ("qrc", False)
        ]:
            var = tk.BooleanVar(value=var_value)
            self.check_vars[var_name] = var

        video_extensions = ["mp4", "avi", "mkv", "flv", "ts", "mov", "wmv", "mp3", "aac", "ape", "flac", "wav", "alac", "ogg"]
        subtitle_extensions = ["srt", "ass", "sub", "ssa", "lrc", "krc", "qrc"]

        for var_name, var in self.check_vars.items():
            tk_check_button = getattr(self.ui, f"tk_check_button_{var_name}")
            tk_check_button.config(variable=var, onvalue=True, offvalue=False)

        for var_name in video_extensions:
            self.video_extensions_vars[var_name] = self.check_vars[var_name]
        for var_name in subtitle_extensions:
            self.subtitle_extensions_vars[var_name] = self.check_vars[var_name]

    def get_vtrue_extension_keys(self):
        return [key for key, value in self.video_extensions_vars.items() if value.get()]

    def get_strue_extension_keys(self):
        return [key for key, value in self.subtitle_extensions_vars.items() if value.get()]

    def get_directory_files(self, directory_path):
        files_dict = {}
        def _process_files(path):
            for entry in os.scandir(path):
                if entry.is_file():
                    name, ext = os.path.splitext(entry.name)
                    files_dict.setdefault(name, []).append(ext)
                elif entry.is_dir():
                    _process_files(entry.path)

        _process_files(directory_path)
        return files_dict

    def find_missing_files(self, files_dict, get_vtrue_extension_keys, get_strue_extension_keys):
        get_vtrue_extension_keys = set(get_vtrue_extension_keys)
        get_strue_extension_keys = set(get_strue_extension_keys)
        missing_video_files = []
        missing_subtitle_files = []
        for name, extensions in files_dict.items():
            if len(extensions) == 1:
                ext = extensions[0]
                if ext.lstrip('.') in get_vtrue_extension_keys:
                    missing_video_files.append(f"缺失字幕： {name}{ext}")
                elif ext.lstrip('.') in get_strue_extension_keys:
                    missing_subtitle_files.append(f"缺失视频： {name}{ext}")

        result = missing_video_files + missing_subtitle_files
        return result

    def s_zt(self,evt):
        print("<<ComboboxSelected>>事件未处理:",evt)
    def directory(self, evt):
        self.directory_path = filedialog.askdirectory()
        self.ui.tk_text_print.delete(1.0, tk.END)  # 清空文本框
        self.ui.tk_input_directory_txt.delete(0, tk.END)  # 清空目录路径输入框
        self.ui.tk_input_directory_txt.insert(0, self.directory_path)  # 写入目录路径输入框

    def start(self, evt):
        self.ui.tk_text_print.delete(1.0, tk.END)  # 清空文本框
        directory_path = self.ui.tk_input_directory_txt.get().strip()  # 获取并去除前后空格
        if directory_path:  # 检查路径是否非空
            files_dict = self.get_directory_files(directory_path)
            get_vtrue_extension_keys = self.get_vtrue_extension_keys()
            get_strue_extension_keys = self.get_strue_extension_keys()

            missing_files = self.find_missing_files(files_dict, get_vtrue_extension_keys, get_strue_extension_keys)
            if not missing_files:
                missing_files = ["没有找到缺失的文件"]
            self.ui.tk_text_print.insert(1.0, "\n".join(missing_files))
        else:
            messagebox.showerror("错误", "请选择或输入一个有效的目录路径")

